package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信相关接口")
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin //跨域
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("发送短信")
    @ApiImplicitParam(name = "phone",value = "手机号",required = true)
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //根据手机号再redis中先取出，看是不是为空
        String code = redisTemplate.opsForValue().get(phone);
        //不为空直接返回
        if(!StringUtils.isEmpty(code)) return R.ok();

        //为空，生成验证码并放再map里面
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);

        //调用service方法进行发送
        boolean isSend = msmService.send(phone,param);

        //判断是否发送成功，发送成功则把验证码存入redis中，设置过期事件5分钟
        if(isSend) {
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }
    }
}
